package com.yuntsg.ruiijn.paperana.test.small;

import com.yuntsg.ruiijn.paperana.test.PDFTextStripper2;
import lombok.SneakyThrows;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import java.io.File;

public class PDF拆分 {
    @SneakyThrows
    public static void main(String[] args) {

        for (int j = 0; j < 20; j++) {
            String parentPath = "E:\\pdfpath\\";
            String fileName = System.currentTimeMillis() + ".pdf";
            String path = "D:\\Users\\55419\\Desktop\\1723603839545___国自然原始文件.pdf";
//            String path = "D:\\Users\\55419\\Desktop\\真国自然原始文件.pdf";
            File file = new File(path);
            PDDocument doc = Loader.loadPDF(file);
            PDDocument docNew = new PDDocument();
            int numberOfPages = doc.getNumberOfPages();
            PDFTextStripper2 stripper2 = new PDFTextStripper2();
            int startPage = 0;
            int endPage = 9999;
            for (int i = 0; i < numberOfPages; i++) {
                stripper2.setStartPage(i);
                stripper2.setEndPage(i);
                String text = "";
                try {
                    text = stripper2.getText(doc);//读取当前页的全部内容
                } catch (Exception e) {

                }
                if (text.contains("参照以下提纲撰写，要求内容翔实、清晰，层次分明，标题突")) {
                    System.out.println("匹配到了+++参照以下提纲撰写，要求内容翔实、清晰，层次分明++" + i);
                    startPage = i;
                }
                if (text.contains("论著之外的代表性研究成果和学术奖励")) {
                    System.out.println("匹配到了+++论著之外的代表性研究成果和学术奖励++" + i);
                    if (i <= endPage) {
                        endPage = i;
                    }

                }
            }
            System.out.println("页码开始+" + startPage);
            System.out.println("页码结束+" + endPage);

            if (startPage > 0 && endPage > 0) {
                for (int i = startPage - 1; i <= endPage; i++) {
                    PDPage page = doc.getPage(i);
                    docNew.addPage(page);
                }
            }
            docNew.save(parentPath + fileName);
            docNew.close();
            doc.close();

        }


//        PDFMergerUtility
//        PDFmerger.setDestinationFileName("D:/PdfBoxExamples/docs/merged.pdf");


    }
}
